package com.deeper.customview.ui.c4.demo.c04d04;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RadialGradient;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

public class FiveChessView extends View {
    private static final int SIZE = 120; //棋子尺寸
    private static final int OFFSET = 10;//发光点的偏移大小
    private Paint paint;


    public FiveChessView(Context context) {
        super(context);
    }


    public FiveChessView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    }


    public FiveChessView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width = getMeasuredWidth();
        int height = getMeasuredHeight();
        int rows = height / SIZE;
        int cols = width / SIZE;
        //画棋盘
        drawChessBoard(canvas, rows, cols);
        //画棋子
        drawChess(canvas, 4, 4, ChessType.BLACK);
        drawChess(canvas, 4, 5, ChessType.BLACK);
        drawChess(canvas, 5, 4, ChessType.WHITE);
        drawChess(canvas, 3, 5, ChessType.WHITE);
    }


    private void drawChessBoard(Canvas canvas, int rows, int cols) {
        //画竖线
        canvas.save();
        canvas.translate(20, 20);

        for (int i = 0; i < cols; i++) {
            canvas.drawLine(0, 0, 0, rows * SIZE, paint);
            canvas.translate(SIZE, 0);
        }
        canvas.restore();

        //画横线
        canvas.save();
        canvas.translate(20, 20);

        for (int i = 0; i < rows + 1; i++) {
            canvas.drawLine(0, 0, (cols - 1) * SIZE, 0, paint);
            canvas.translate(0, SIZE);
        }
        canvas.restore();
    }


    private void drawChess(Canvas canvas, int row, int col, ChessType chessType) {
        canvas.save();
        canvas.translate(20, 20);

        canvas.translate(row * SIZE, col * SIZE);
        int color = chessType == ChessType.BLACK ? Color.BLACK : Color.GRAY;
        RadialGradient rg = new RadialGradient(0 + OFFSET, 0 + OFFSET, SIZE / 2, Color.WHITE, color, Shader.TileMode.MIRROR);
        paint.setShader(rg);
        canvas.drawCircle(0, 0, SIZE / 2, paint);
        canvas.restore();
    }


    enum ChessType {
        BLACK, WHITE
    }
}
